package com.xspace.android.xafcommon.db.dbsub;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.xspace.android.xafcommon.db.BaseSql;
import com.xspace.android.xafcommon.db.SDBaseSql;

import java.util.ArrayList;

import cn.xspace.app.filemg.bean.FileInfo;
import cn.xspace.app.filemg.bean.ImgPackInfo;


public class FileMgDb extends BaseSql {

	public static String TABLE_NAME = "sendTable";
	public static String SENDTYPE = "speedType";
	public static String sendObject = "sendObject";

	public FileMgDb(MyDBHelper db) {
		super(db);
	}

	public FileMgDb() {

	}

	@Override
	public void create(SQLiteDatabase db) {
		db.execSQL("CREATE TABLE " + TABLE_NAME + " (_ID INTEGER PRIMARY " + "KEY AUTOINCREMENT," + SENDTYPE
				+ " varchar(16) ," + sendObject + " BLOB);");

	}

	public void dropTable(SQLiteDatabase db) {
		db.execSQL(TB_DELETE + TABLE_NAME);
	}

	@Override
	public void upgrade(SQLiteDatabase db) {
	}

	public int saveOrUpdate(String sendType, ArrayList<FileInfo> list) {
		where = SENDTYPE + "='" + sendType + "'";
		values = new ContentValues();
		values.put(SENDTYPE, sendType);
		values.put(sendObject, getBytesFromObject(list));
		return super.saveOrUpdate(TABLE_NAME);
	}

	public int saveOrUpdateImg(String sendType, ArrayList<ImgPackInfo> list) {
		where = SENDTYPE + "='" + sendType + "'";
		values = new ContentValues();
		values.put(SENDTYPE, sendType);
		values.put(sendObject, getBytesFromObject(list));
		return super.saveOrUpdate(TABLE_NAME);
	}

	public ArrayList<FileInfo> querySend(String sendType) {
		ArrayList<FileInfo> list = new ArrayList<FileInfo>();
		try {
			String sql = SENDTYPE + "='" + sendType + "'";
			try {
				Cursor cur = db.query(TABLE_NAME, sql);
				if (cur != null) {
					System.out.println("--------------------cur.getCount():" + cur.getCount());
					if (cur.getCount() != 0) {
						cur.moveToFirst();
						try {
							list = (ArrayList<FileInfo>) getObjectFromBytes(
									cur.getBlob(cur.getColumnIndex(sendObject)));
						} catch (Exception e) {
							e.printStackTrace();
						}

					}
					cur.close();
				}
				db.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}

	public ArrayList<ImgPackInfo> querySendImg(String sendType) {
		ArrayList<ImgPackInfo> list = new ArrayList<ImgPackInfo>();
		where = sendType + "='" + sendType + "'";
		Cursor cur = db.query(TABLE_NAME, null);
		if (cur != null) {
			if (cur.getCount() != 0) {
				cur.moveToFirst();
				list = (ArrayList<ImgPackInfo>) getObjectFromBytes(cur.getBlob(cur.getColumnIndex(sendObject)));

			}
			cur.close();
		}
		db.close();
		return list;
	}

	public int delete(String sendType) {
		selection = SENDTYPE + "=?";
		selectionArgs = new String[] { sendType };
		return super.delete(TABLE_NAME);
	}
}
